﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Web.Script.Serialization;
using System.Web;
using System.IO;
using System.Text;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Net;
using System.Configuration;
using System.Diagnostics;
using Model;
namespace Common
{
    public class Commons
    {
        public static string domain = "http://www.mengshen666.cn";
        public static int PageSize = 20;
        public static Dictionary<int, string> ActiveState = new Dictionary<int, string>(); //订单状态
        public static Dictionary<int, string> PrizeType = new Dictionary<int, string>(); //领奖方式
        public static Dictionary<int, string> RoleName = new Dictionary<int, string>(); //会员级别
        public static Dictionary<int, string> StateText = new Dictionary<int, string>(); //审核状态
        public static Dictionary<int, string> ReduceState = new Dictionary<int, string>(); //扣量状态
        static Commons()
        {
            ActiveState.Add(0, "未知状态");
            ActiveState.Add(1, "投放中");
            ActiveState.Add(2, "已暂停");
            ActiveState.Add(3, "已结束");
            ActiveState.Add(4, "已暂停");

            RoleName.Add(0, "未知");
            RoleName.Add(1, "普通会员");
            RoleName.Add(2, "商家会员");

            PrizeType.Add(0, "未知");
            PrizeType.Add(1, "直接领奖");
            PrizeType.Add(2, "分享领奖");
            PrizeType.Add(3, "语音红包");
            PrizeType.Add(4, "积攒活动");
            PrizeType.Add(5, "分享活动");

            StateText.Add(-1, "");
            StateText.Add(0, "未审核");
            StateText.Add(1, "已通过");
            StateText.Add(2, "已拒绝");

            ReduceState.Add(0, "未知状态");
            ReduceState.Add(1, "执行中");
            ReduceState.Add(2, "已暂停");
            ReduceState.Add(3, "已结束");
        }
        public static string GetSuccess(string msg, object data)
        {
            dynamic dy = new ExpandoObject();
            dy.state = true;
            dy.msg = msg;
            dy.data = data;
            return SerializeHelper.ToJsonByDynamic(dy);
        }

        public static string GetSuccessByWeiXin(string msg, object url)
        {
            dynamic dy = new ExpandoObject();
            dy.state = true;
            dy.url = url;
            return SerializeHelper.ToJsonByDynamic(dy);
        }

        public static string GetFaild(string msg)
        {
            dynamic dy = new ExpandoObject();
            dy.state = false;
            dy.msg = msg;
            return SerializeHelper.ToJsonByDynamic(dy);
        }
        //获取config文件value
        public static string GetConfig(string key)
        {
            if (!string.IsNullOrEmpty(key) &&
                ConfigurationManager.AppSettings.AllKeys.Contains(key))
            {
                return ConfigurationManager.AppSettings[key].ToString();
            }
            return string.Empty;
        }
        public static void ReStartServer()
        {
            try
            {
                Process[] processes = Process.GetProcesses();
                foreach (Process p in processes)
                {
                    if (p.ProcessName == "House")
                    {
                        p.Kill();
                    }
                }
                System.Diagnostics.Process.Start("D:/www/houseserver/House.exe");
            }
            catch (Exception)
            {
            }
        }
        public static string FilterHTML(string str)
        {
            str = Regex.Replace(str, @"<[\s\S]*?>", "");
            return str.Replace("&nbsp;", "");
        }
        /// <summary>
        /// URL字符编码
        /// </summary>
        public static string UrlEncode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            str = str.Replace("'", "");
            return HttpContext.Current.Server.UrlEncode(str);
        }

        /// <summary>
        /// URL字符解码
        /// </summary>
        public static string UrlDecode(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return "";
            }
            return HttpContext.Current.Server.UrlDecode(str);
        }
        public static string GetWebClientIP()
        {

            string userIP = "未获取用户IP";

            try
            {
                if (System.Web.HttpContext.Current == null
            || System.Web.HttpContext.Current.Request == null
            || System.Web.HttpContext.Current.Request.ServerVariables == null)
                    return "";

                string CustomerIP = "";

                //CDN加速后取到的IP simone 090805
                CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }

                CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];


                if (!String.IsNullOrEmpty(CustomerIP))
                    return CustomerIP;

                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (CustomerIP == null)
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                else
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                }

                if (string.Compare(CustomerIP, "unknown", true) == 0)
                    return System.Web.HttpContext.Current.Request.UserHostAddress;
                return CustomerIP;
            }
            catch { }

            return userIP;

        }
        /// <summary> 
        /// 取得客户端真实IP。如果有代理则取第一个非内网地址 
        /// </summary> 
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (result != null && result != String.Empty)
                {
                    //可能有代理 
                    if (result.IndexOf(".") == -1)     //没有“.”肯定是非IPv4格式 
                        result = null;
                    else
                    {
                        if (result.IndexOf(",") != -1)
                        {
                            //有“,”，估计多个代理。取第一个不是内网的IP。 
                            result = result.Replace(" ", "").Replace("'", "");
                            string[] temparyip = result.Split(",;".ToCharArray());
                            for (int i = 0; i < temparyip.Length; i++)
                            {
                                if (IsIPAddress(temparyip[i])
                                    && temparyip[i].Substring(0, 3) != "10."
                                    && temparyip[i].Substring(0, 7) != "192.168"
                                    && temparyip[i].Substring(0, 7) != "172.16.")
                                {
                                    return temparyip[i];     //找到不是内网的地址 
                                }
                            }
                        }
                        else if (IsIPAddress(result)) //代理即是IP格式 
                            return result;
                        else
                            result = null;     //代理中的内容 非IP，取IP 
                    }
                }
                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];


                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

                if (result == null || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;
                return result;
            }

        }
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;
            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        public static string GetWeek()
        {
            string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            return Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
        }
        public static string getMonthDay(DateTime date)
        {
            string year_day = "";
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.Month + "月" + date.Day + "日 ";
                }
            }
            else
            {
                year_day = date.Month + "月" + date.Day + "日 ";
            }

            return year_day;
        }
        public static string getMonthDayHourMinute(DateTime date)
        {
            string year_day = "";
            string minite = date.Minute.ToString();
            if (date.Year == DateTime.Now.Year && date.Month == DateTime.Now.Month)
            {
                if (date.Day == DateTime.Now.Day)
                {
                    year_day = "今天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 1))
                {
                    year_day = "昨天 ";
                }
                else if (date.Day == (DateTime.Now.Day - 2))
                {
                    year_day = "前天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 1))
                {
                    year_day = "明天 ";
                }
                else if (date.Day == (DateTime.Now.Day + 2))
                {
                    year_day = "后天 ";
                }
                else
                {
                    year_day = date.Month + "月" + date.Day + "日 ";
                }
            }
            else
            {
                year_day = date.Month + "月" + date.Day + "日 ";
            }
            if (minite.Length < 2)
            {
                minite = "0" + minite;
            }
            return year_day + date.Hour + ":" + minite;
        }
        /// <summary>
        /// 计算两个日期的时间间隔,返回的是时间间隔的日期差的绝对值.
        /// </summary>
        /// <param name="DateTime1">第一个日期和时间</param>
        /// <param name="DateTime2">第二个日期和时间</param>
        /// <returns></returns>
        public static int DateDiff(DateTime DateTime1, DateTime DateTime2, string Flag)
        {
            double dateDiff = 0;
            try
            {
                TimeSpan ts1 = new TimeSpan(DateTime1.Ticks);
                TimeSpan ts2 = new TimeSpan(DateTime2.Ticks);
                TimeSpan ts = ts1.Subtract(ts2).Duration();
                if (Flag == "Y")
                {
                    dateDiff = ts.TotalDays / 365;
                }
                else if (Flag == "D")
                {
                    dateDiff = ts.TotalDays;
                }
                else if (Flag == "H")
                {
                    dateDiff = ts.TotalHours;
                }
                else if (Flag == "M")
                {
                    dateDiff = ts.TotalMinutes;
                }
                else if (Flag == "S")
                {
                    dateDiff = ts.TotalSeconds;
                }

            }
            catch
            {
            }
            return (int)dateDiff;
        }
        public static void Log(string str)
        {
            string path = HttpContext.Current.Server.MapPath("/log.txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true);//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine("=======================" + DateTime.Now + "=======================");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
        }
        public static void Log2(string str)
        {
            string path = HttpContext.Current.Server.MapPath("/log2.txt");
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true);//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine("=======================" + DateTime.Now + "=======================");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
        }
        public static string Ewm(string str)
        {
            string file = "/upload/ewm/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".txt";
            string path = HttpContext.Current.Server.MapPath(file);
            if (!System.IO.File.Exists(path))
            {
                System.IO.FileStream f = System.IO.File.Create(path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(path, true);//true为追加,false为覆盖
            System.Text.Encoding.GetEncoding("gb2312");
            f2.WriteLine(str);
            f2.Close();
            f2.Dispose();
            return file;
        }
        public static bool CheckSign()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                string action = JobRequest.GetRequestString("act");
                string sign = JobRequest.GetRequestString("sign");
                sb.AppendFormat("account={0}&act={1}&key={2}", "XinLian_MOBILE_CLIENT", action, "365E6B86CE4E43A552G563078D5ADEFD");
                string signstr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sb.ToString(), "MD5").ToLower();
                Commons.Log(sign+"---"+signstr);
                return sign == signstr;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public static string SubString(string str, int len)
        {
            if (str.Length > len)
            {
                return str.Substring(0, len);
            }
            else
            {
                return str;
            }
        }

        /// <summary>
        /// 生成订单号
        /// </summary>
        /// <param name="head">前缀，比如:PO</param>
        /// <param name="num">单号</param>
        /// <returns></returns>
        public static string ToNum(string head, string num)
        {
            var newnum = "";
            var date = DateTime.Now.ToString("yyyyMMdd");
            if (num == "" || num == null)
            {
                newnum = head + date + "0001";
            }
            else
            {
                if (num.Length == 14)
                {
                    int maxnum = int.Parse(num.Substring(10, 4)) + 1;
                    if (maxnum.ToString().Length == 1)
                    {
                        newnum = newnum = head + date + "000" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 2)
                    {
                        newnum = newnum = head + date + "00" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 3)
                    {
                        newnum = newnum = head + date + "0" + maxnum;
                    }
                    else if (maxnum.ToString().Length == 4)
                    {
                        newnum = newnum = head + date + maxnum;
                    }
                    else { }
                }
            }
            return newnum;
        }

        public static string AddDou(string str)
        {
            return "," + str.Trim(',') + ",";
        }

        public static bool SqlFilter(string InText)
        {
            string word = "and|exec|insert|select|delete|update|chr|mid|master|or|truncate|char|declare|join";
            if (InText == null)
                return false;
            foreach (string i in word.Split('|'))
            {
                if ((InText.ToLower().IndexOf(i + " ") > -1) || (InText.ToLower().IndexOf(" " + i) > -1))
                {
                    return true;
                }
            }
            return false;
        }
        public static string GetImg(string path, int size)
        {
            string[] files = path.Split('.');
            string ext = "." + files[files.Length - 1];
            return path.Replace(ext, "") + "_" + size + ext;
        }

        public static string TranRN(string str)
        {
            return str.Replace("\r\n", "<br>").Replace("\r", "<br>").Replace("\n", "<br>").Replace(" ", "&nbsp;");
        }

        //计算距离
        public static double CalcDistance(double fromX, double fromY, double toX, double toY)
        {
            double rad = 6371; //Earth radius in Km

            //Convert to radians

            double p1X = fromX / 180 * Math.PI;

            double p1Y = fromY / 180 * Math.PI;

            double p2X = toX / 180 * Math.PI;

            double p2Y = toY / 180 * Math.PI;

            return Math.Acos(Math.Sin(p1Y) * Math.Sin(p2Y) +

                Math.Cos(p1Y) * Math.Cos(p2Y) * Math.Cos(p2X - p1X)) * rad * 1000;
        }
        public static string NoScript(string Htmlstring)
        {
            return Regex.Replace(Htmlstring, @"<script([^>])*>(\w|\W)*?</script([^>])*>", "", RegexOptions.IgnoreCase);
        }
        public static string DownImg(string html)
        {
            WeiXin wx = new WeiXin();
            Regex regImg1 = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            //新建一个matches的MatchCollection对象 保存 匹配对象个数(img标签)
            MatchCollection matches1 = regImg1.Matches(html);
            string fold = DateTime.Now.ToString("yyyy-MM-dd");
            string path = HttpContext.Current.Server.MapPath("/upload/" + fold);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            int count = 0;
            foreach (Match matches in matches1)
            {
                if (matches.Groups["imgUrl"].Value.StartsWith("http"))
                {
                    count++;
                    string img = matches.Groups["imgUrl"].Value;

                    string ext = "gif";
                    if (img.Split('=').Length >= 2)
                    {
                        ext = img.Split('=')[img.Split('=').Length - 1];
                    }
                    if (ext.Length != 3)
                    {
                        ext = "png";
                    }
                    string file="/upload/"+fold +"/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + count + "." + ext;
                    wx.SaveFile(img, file);
                    html=html.Replace(img,file);
                }
            }
            return html;
        }
        public static string GetToken()
        {
            return Guid.NewGuid().ToString("N");
        }
    }
}
